<?php
declare (strict_types=1);

namespace addons\Builder\driver;

use addons\Builder\driver\trait\TableBase;
use addons\Builder\facade\Builder;
use app\common\tool\Result;
use think\facade\Cache;

class TableTool
{
    use TableBase;

    public function test()
    {
        $task = config('tool')['task'];
        foreach ($task as &$item) {
            $item['record'] = $this->getRecord($item['type']);
        }
        $arguments['task'] = $task;

        return Builder::TableCache()->getView('test', true, $arguments);
    }

    public function getRecord($type)
    {
        $list = Cache::get('TableToolTask_' . $type);
        if (empty($list)) {
            return [];
        }
        $sort = [];
        foreach ($list as &$v) {
            $sort[] = $v['times'];
        }
        array_multisort($sort, SORT_DESC, $list);
        return $list;
    }

    public function execute()
    {
        try {

            $param = $this->request->post();
            $t1 = microtime(true);
            $task = config('tool')['task'];
            foreach ($task as &$item) {
                if ($item['type'] == $param['type']) {
                    $execute = $item['execute'];
                    $type = $item['type'];
                    $result = $item['param'] ? $execute::$type($item['param']) : $execute::$type();
                    break;
                }
            }
            $msg = $result['code'] == 1 ? 'success' : 'error：' . $result['msg'];
            $t2 = microtime(true);
            $data['admin'] = $this->request->admin['admin_name'];
            $data['times'] = time();
            $data['method'] = $this->request->action();
            $data['ip'] = $this->request->ip();
            $data['required'] = round($t2 - $t1, 6);
            $data['status'] = $msg;
            $list = Cache::get('TableToolTask_' . $param['type']);
            $list[] = $data;
            Cache::set('TableToolTask_' . $param['type'], $list);
            return Result::fastReturn($result);
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }

    }
}
